package com.engine.wei.base.utils;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;


import com.engine.wei.base.utils.log.LogUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

/**
 * 作者:赵若位
 * 时间:2020/12/23 10:56
 * Update:2021/7/15 17:46
 * 功能:Activity堆栈管理
 */
public final class ActivityStackManager implements Application.ActivityLifecycleCallbacks, LifecycleObserver {

    //
    private static final byte[] LOCK = new byte[0];
    //饿汉单例
    private static ActivityStackManager sManager = new ActivityStackManager();
    //Activity堆栈
    private final List<Activity> sActivities;
    //应用前后台监听
    private final List<OnAppBackgroundListener> mAppGroundListeners = new ArrayList<>();

    private ActivityStackManager() {
        sActivities = new ArrayList<>();
    }

    public static ActivityStackManager getInstance() {
        return sManager;
    }

    @Override
    public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
        if (null != activity) {
            sActivities.add(activity);
        }
    }

    @Override
    public void onActivityStarted(@NonNull Activity activity) {

    }

    @Override
    public void onActivityResumed(@NonNull Activity activity) {

    }

    @Override
    public void onActivityPaused(@NonNull Activity activity) {

    }

    @Override
    public void onActivityStopped(@NonNull Activity activity) {
    }

    @Override
    public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(@NonNull Activity activity) {
        if (null != activity) {
            sActivities.remove(activity);
        }
    }

    /*获取栈顶的Activity*/
    public Activity getTopActivity() {
        return !sActivities.isEmpty() ? sActivities.get(sActivities.size() - 1) : null;
    }

    /*获取栈顶活动的Activity*/
    public Activity getLastSurviveActivity() {
        if (null == sActivities || sActivities.isEmpty()) {
            return null;
        }
        ListIterator<Activity> iterator = sActivities.listIterator(sActivities.size());
        while (iterator.hasPrevious()) {
            Activity activity = iterator.previous();
            if (null != activity && !activity.isFinishing()) {
                return activity;
            }
        }
        return getTopActivity();
    }

    private void clearStack() {
        for (Activity activity : sActivities) {
            if (null != activity) {
                activity.finish();
            }
        }
        sActivities.clear();
    }


    /*移除指定的Activity*/
    public void finish(Activity activity) {
        if (null != activity && sActivities.contains(activity)) {
            sActivities.remove(activity);
            activity.finish();
        }
    }

    /*移除指定的Activity*/
    public void finish(Class<? extends Activity> cls) {
        if (null != cls && !sActivities.isEmpty()) {
            for (Activity activity : sActivities) {
                if (activity.getClass().equals(cls)) {
                    sActivities.remove(activity);
                    activity.finish();
                    return;
                }
            }
        }
    }

    /**
     * 退出应用程序
     * 此方法经测试在某些机型上并不能完全杀死 App 进程, 几乎试过市面上大部分杀死进程的方式, 但都发现没卵用, 所以此
     * 方法如果不能百分之百保证能杀死进程, 就不能贸然释放资源, 否则会造成其他问题, 如果您
     * 有测试通过的并能适用于绝大多数机型的杀死进程的方式, 望告知
     */
    public void exit() {
        try {
            clearStack();
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addAppBackgroundListener(OnAppBackgroundListener listener) {
        synchronized (LOCK) {
            if (null != listener) {
                mAppGroundListeners.add(listener);
            }
        }
    }

    public void removeAppBackgroundListener(OnAppBackgroundListener listener) {
        synchronized (LOCK) {
            if (null != listener) {
                mAppGroundListeners.remove(listener);
            }
        }
    }

    private void handAppBackgroundListeners(boolean isForeground) {
        synchronized (LOCK) {
            if (null != mAppGroundListeners && !mAppGroundListeners.isEmpty()) {
                for (OnAppBackgroundListener listener : mAppGroundListeners) {
                    if (null != listener) {
                        listener.onGround(isForeground);
                    }
                }
            }
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    private void onAppBackground() {
        // 应用进入后台
        LogUtils.i("应用进入后台");
        handAppBackgroundListeners(false);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    private void onAppForeground() {
        // 应用进入前台
        LogUtils.i("应用进入前台");
        handAppBackgroundListeners(true);
    }


    /*应用前后台监听*/
    public interface OnAppBackgroundListener {
        void onGround(boolean isForeground);
    }
}

